<template>
  <div class="reviews-container">
    <div class="header-nav">
      <el-button
          type="primary"
          icon="el-icon-back"
          @click="goBack"
          class="back-btn"
      >
        返回首页
      </el-button>
    </div>
    <el-card class="reviews-card">
      <div slot="header">
        <h2>{{ bookTitle }} 的评论</h2>
        <el-button
            type="primary"
            size="small"
            @click="showAddDialog"
            icon="el-icon-edit"
        >
          添加评论
        </el-button>
      </div>

      <div v-if="reviews.length > 0">
        <div v-for="(review, index) in reviews" :key="review.id" class="review-item">
          <div class="review-header">
            <el-tooltip effect="dark" :content="review.author || '匿名用户'" placement="top">
              <span class="review-author">{{ review.author || '匿名用户' }}</span>
            </el-tooltip>
            <span class="review-date">{{ formatDate(review.date) }}</span>
          </div>

          <div v-if="review.editing" class="review-edit">
            <el-input
                type="textarea"
                v-model="review.editContent"
                :rows="3"
                placeholder="请输入评论内容"
                maxlength="500"
                show-word-limit
            ></el-input>
            <div class="review-actions">
              <el-button size="mini" @click="cancelEdit(index)">取消</el-button>
              <el-button
                  type="primary"
                  size="mini"
                  @click="saveEdit(index)"
                  :disabled="!review.editContent.trim()"
              >
                保存
              </el-button>
            </div>
          </div>
          <div v-else class="review-content">
            {{ review.content }}
          </div>

          <div class="review-actions" v-if="!review.editing">
            <el-button
                size="mini"
                @click="startEdit(index)"
                icon="el-icon-edit"
                v-if="review.author === '当前用户' || !review.author"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                size="mini"
                @click="deleteReview(index)"
                icon="el-icon-delete"
                v-if="review.author === '当前用户' || !review.author"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      <div v-else class="no-reviews">
        暂无评论，快来添加第一条评论吧！
      </div>
    </el-card>

    <el-dialog
        title="添加评论"
        :visible.sync="dialogVisible"
        width="50%"
        @close="handleDialogClose"
    >
      <el-input
          type="textarea"
          v-model="newReviewContent"
          :rows="5"
          placeholder="请输入评论内容（最多500字）"
          maxlength="500"
          show-word-limit
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
            type="primary"
            @click="addReview"
            :disabled="!newReviewContent.trim()"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ReviewsView',
  data() {
    return {
      bookId: null,
      bookTitle: '',
      reviews: [],
      dialogVisible: false,
      newReviewContent: '',
      currentBook: null
    };
  },
  created() {
    if (!this.$store.state.user) {
      this.$message.warning('请先登录');
      this.$router.push({
        path: '/login',
        query: {
          redirect: '/reviews',
          bookId: this.$route.query.bookId
        }
      });
      return;
    }

    this.bookId = this.$route.query.bookId;
    this.loadBookData();
    this.loadReviews();
  },
  methods: {
    loadBookData() {
      const allBooks = [
        { id: 1, title: "红楼梦", author: "曹雪芹", price: 45.8 },
        { id: 2, title: "活着", author: "余华", price: 28.5 },
        { id: 3, title: "围城", author: "钱钟书", price: 36.0 },
        { id: 4, title: "三体", author: "刘慈欣", price: 56.0 },
        { id: 5, title: "神经漫游者", author: "威廉·吉布森", price: 42.9 },
        { id: 6, title: "沙丘", author: "弗兰克·赫伯特", price: 65.0 },
        { id: 7, title: "史记", author: "司马迁", price: 68.0 },
        { id: 8, title: "资治通鉴", author: "司马光", price: 75.5 },
        { id: 9, title: "万历十五年", author: "黄仁宇", price: 32.8 },
        { id: 10, title: "艺术的故事", author: "贡布里希", price: 228.0 },
        { id: 11, title: "现代艺术150年", author: "威尔·贡培兹", price: 88.0 },
        { id: 12, title: "写给大家的西方美术史", author: "蒋勋", price: 56.0 },
        { id: 13, title: "时间简史", author: "霍金", price: 45.0 },
        { id: 14, title: "人类简史", author: "尤瓦尔·赫拉利", price: 68.0 },
        { id: 15, title: "如何阅读一本书", author: "莫提默·J. 艾德勒", price: 38.0 }
      ];

      this.currentBook = allBooks.find(book => book.id == this.bookId);
      if (this.currentBook) {
        this.bookTitle = this.currentBook.title;
      }
    },
    loadReviews() {
      const savedReviews = JSON.parse(localStorage.getItem('bookReviews')) || {};
      this.reviews = savedReviews[this.bookId] || [];

      this.reviews = this.reviews.map(review => ({
        ...review,
        editing: false,
        editContent: review.content || ''
      }));

      if (this.reviews.length === 0) {
        this.reviews = [
          {
            id: 1,
            content: "这是一本非常棒的书，值得一读！",
            author: "用户A",
            date: new Date(Date.now() - 3600000 * 24),
            editing: false,
            editContent: "这是一本非常棒的书，值得一读！"
          },
          {
            id: 2,
            content: "内容深刻，发人深省。",
            author: "用户B",
            date: new Date(Date.now() - 3600000 * 48),
            editing: false,
            editContent: "内容深刻，发人深省。"
          }
        ];
        this.saveReviews();
      }
    },
    saveReviews() {
      const savedReviews = JSON.parse(localStorage.getItem('bookReviews')) || {};
      savedReviews[this.bookId] = this.reviews.map(review => ({
        ...review,
        content: review.content,
        editContent: ''
      }));
      localStorage.setItem('bookReviews', JSON.stringify(savedReviews));
    },
    showAddDialog() {
      this.newReviewContent = '';
      this.dialogVisible = true;
    },
    addReview() {
      if (!this.newReviewContent.trim()) {
        this.$message.warning('评论内容不能为空');
        return;

      }

      const newReview = {
        id: Date.now(),
        content: this.newReviewContent,
        author: '当前用户',
        date: new Date(),
        editing: false,
        editContent: this.newReviewContent
      };

      this.reviews.unshift(newReview);
      this.saveReviews();
      this.dialogVisible = false;
      this.$message.success('评论添加成功');
    },
    startEdit(index) {
      const review = {...this.reviews[index]};
      review.editing = true;
      review.editContent = review.content;
      this.$set(this.reviews, index, review);
    },
    cancelEdit(index) {
      const review = {...this.reviews[index]};
      review.editing = false;
      review.editContent = review.content;
      this.$set(this.reviews, index, review);
    },
    saveEdit(index) {
      if (!this.reviews[index].editContent.trim()) {
        this.$message.warning('评论内容不能为空');
        return;
      }

      const review = {...this.reviews[index]};
      review.content = review.editContent;
      review.editing = false;
      this.$set(this.reviews, index, review);
      this.saveReviews();
      this.$message.success('评论修改成功');
    },
    deleteReview(index) {
      this.$confirm('确定要删除这条评论吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.reviews.splice(index, 1);
        this.saveReviews();
        this.$message.success('评论删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleDialogClose() {
    },
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
    },
    goBack() {
      if (window.history.length > 1) {
        this.$router.go(-1);
      } else {
        this.$router.push('/home');
      }
    }
  }
};
</script>

<style scoped>
.reviews-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.reviews-card {
  margin-top: 20px;
}

.review-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
}

.review-author {
  margin-right: 15px;
  font-weight: bold;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.review-date {
  color: #999;
  font-size: 13px;
}

.review-content {
  margin: 10px 0;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.review-actions {
  margin-top: 10px;
}

.no-reviews {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.header-nav {
  margin-bottom: 20px;
}

.el-textarea {
  font-size: 14px;
}
</style>